package com.tangcheng.redislistener.expire.job;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.time.Duration;
import java.time.LocalDateTime;
import java.util.concurrent.ThreadLocalRandom;

import static com.tangcheng.redislistener.expire.listener.CustomMessageListener.CUSTOM_CHANNEL_PREFIX;

@Service
@Slf4j
public class RedisPubJob {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Value("${server.port:8080}")
    private int serverPort;

    @Scheduled(cron = "0 */1 * * * ?")
    public void pubMsg() {
        LocalDateTime now = LocalDateTime.now();
        log.info("开始发送消息");
        int value = ThreadLocalRandom.current().nextInt();
        redisTemplate.convertAndSend(CUSTOM_CHANNEL_PREFIX + value, serverPort);
        log.info("消息发送完成: " + Duration.between(now, LocalDateTime.now()));
    }

}